package com.ochnas.examples.jsf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.ochnas.examples.jsf.domain.Bike;
import com.ochnas.examples.jsf.service.RentABike;

public class SubmitBikeController extends SimpleFormController {

	private RentABike facade;
	
	public void setRentABike(RentABike facade) {
		this.facade = facade;
	}
	
	@Override
	public ModelAndView onSubmit(Object commandName) throws ServletException {
		Bike bike = (Bike)commandName; 
				
		facade.saveBike(bike);
		return new ModelAndView(new RedirectView(getSuccessView()), "rentaBike", facade);
		
	}

	public SubmitBikeController() {
		// need a session to hold the formBackingObject
		setSessionForm(true);
		// initialize the form from the formBackingObject
		setBindOnNewForm(true);
	}
	
	/**
      * Set the name of the view that should be used for form display.
      */
	
	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		
		Bike bike = new Bike();
		if(request.getParameter("bikeSerialNo") != null) {
			bike = facade.getBike(request.getParameter("bikeSerialNo"));
		}
		
		return bike;
	}
		
	public RentABike getFacade() {
		return facade;
	}
	public void setFacade(RentABike facade) {
		this.facade = facade;
	}

}
